<template>
  <div class="dashboard">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="back-btn" @click="$router.go(-1)">
        <span class="back-arrow">‹</span>
      </div>
      <h1>医院实时状态</h1>
      <div class="time">{{ currentTime }}</div>
    </div>

    <!-- 数据概览卡片 -->
    <div class="overview">
      <div class="card available-doctors">
        <div class="card-title">可预约医生</div>
        <div class="card-value">{{ stats.availableDoctors }}</div>
        <div class="card-desc">当前在线医生</div>
      </div>
      <div class="card waiting-time">
        <div class="card-title">平均等待时间</div>
        <div class="card-value">{{ stats.avgWaitingTime }}分钟</div>
        <div class="card-desc">预计等待时长</div>
      </div>
      <div class="card available-beds">
        <div class="card-title">剩余床位</div>
        <div class="card-value">{{ stats.availableBeds }}</div>
        <div class="card-desc">当前可用床位</div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts">
      <!-- 各科室等待情况 -->
      <div class="chart-container">
        <div class="chart-header">
          <div class="chart-title">各科室等待情况</div>
          <div class="chart-legend">
            <span class="legend-item">
              <span class="dot low"></span>等待人数少
            </span>
            <span class="legend-item">
              <span class="dot medium"></span>等待适中
            </span>
            <span class="legend-item">
              <span class="dot high"></span>等待人数多
            </span>
          </div>
        </div>
        <div id="waitingChart" class="chart"></div>
      </div>

      <!-- 医生在线状态 -->
      <div class="chart-container">
        <div class="chart-header">
          <div class="chart-title">医生在线状态</div>
          <div class="chart-legend">
            <span class="legend-item">
              <span class="dot available"></span>可预约
            </span>
            <span class="legend-item">
              <span class="dot busy"></span>就诊中
            </span>
            <span class="legend-item">
              <span class="dot offline"></span>暂不可约
            </span>
          </div>
        </div>
        <div id="doctorChart" class="chart"></div>
      </div>

      <!-- 今日就诊趋势 -->
      <div class="chart-container">
        <div class="chart-header">
          <div class="chart-title">今日就诊趋势</div>
          <div class="chart-desc">实时更新各时段就诊人数</div>
        </div>
        <div id="trendChart" class="chart"></div>
      </div>

      <!-- 床位使用情况 -->
      <div class="chart-container">
        <div class="chart-header">
          <div class="chart-title">床位使用情况</div>
          <div class="chart-desc">各科室床位实时状态</div>
        </div>
        <div id="bedChart" class="chart"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'

// 统计数据
const stats = ref({
  availableDoctors: 0,
  avgWaitingTime: 0,
  availableBeds: 0
})

// 当前时间
const currentTime = ref('')
let timer: number

// 图表实例
let waitingChart: any = null
let doctorChart: any = null
let trendChart: any = null
let bedChart: any = null

// 更新等待人数图表
const updateWaitingChart = () => {
  if (!waitingChart) return

  const departments = ['内科', '外科', '儿科', '妇科', '眼科', '口腔科', '骨科', '皮肤科']
  const data = departments.map(() => Math.floor(Math.random() * 50))

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: {c}人等待'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: departments,
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '等待人数'
    },
    series: [{
      type: 'bar',
      data: data.map(value => ({
        value,
        itemStyle: {
          color: value > 30 ? '#ff4d4f' : value > 15 ? '#faad14' : '#52c41a'
        }
      })),
      barWidth: '60%'
    }]
  }

  waitingChart.setOption(option)
}

// 更新医生状态图表
const updateDoctorChart = () => {
  if (!doctorChart) return

  const data = [
    { value: Math.floor(Math.random() * 20) + 10, name: '可预约' },
    { value: Math.floor(Math.random() * 15) + 5, name: '就诊中' },
    { value: Math.floor(Math.random() * 10) + 5, name: '暂不可约' }
  ]

  stats.value.availableDoctors = data[0].value

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}人'
    },
    series: [{
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: true,
        position: 'outside',
        formatter: '{b}\n{c}人'
      },
      data: [
        { ...data[0], itemStyle: { color: '#52c41a' } },
        { ...data[1], itemStyle: { color: '#faad14' } },
        { ...data[2], itemStyle: { color: '#ff4d4f' } }
      ]
    }]
  }

  doctorChart.setOption(option)
}

// 更新就诊趋势图表
const updateTrendChart = () => {
  if (!trendChart) return

  const hours = Array.from({ length: 24 }, (_, i) => `${i}:00`)
  const data = hours.map(() => Math.floor(Math.random() * 30))

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}时: {c}人'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: hours,
      axisLabel: {
        interval: 2
      }
    },
    yAxis: {
      type: 'value',
      name: '就诊人数'
    },
    series: [{
      type: 'line',
      smooth: true,
      data: data,
      areaStyle: {
        opacity: 0.3,
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#1890ff' },
          { offset: 1, color: '#fff' }
        ])
      },
      itemStyle: {
        color: '#1890ff'
      }
    }]
  }

  trendChart.setOption(option)
}

// 更新床位使用图表
const updateBedChart = () => {
  if (!bedChart) return

  const departments = ['内科', '外科', '儿科', '妇科', '急诊']
  const totalBeds = [50, 40, 30, 30, 20]
  const usedBeds = departments.map((_, i) => Math.floor(Math.random() * totalBeds[i]))
  
  stats.value.availableBeds = totalBeds.reduce((a, b) => a + b, 0) - usedBeds.reduce((a, b) => a + b, 0)

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const dataIndex = params[0].dataIndex
        return `${departments[dataIndex]}<br/>已用: ${usedBeds[dataIndex]}<br/>总数: ${totalBeds[dataIndex]}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: departments
    },
    yAxis: {
      type: 'value',
      name: '床位数'
    },
    series: [
      {
        type: 'bar',
        stack: 'total',
        name: '已用',
        data: usedBeds,
        itemStyle: {
          color: '#ff4d4f'
        }
      },
      {
        type: 'bar',
        stack: 'total',
        name: '空闲',
        data: totalBeds.map((total, i) => total - usedBeds[i]),
        itemStyle: {
          color: '#52c41a'
        }
      }
    ]
  }

  bedChart.setOption(option)
}

// 更新时间
const updateTime = () => {
  const now = new Date()
  const hours = now.getHours().toString().padStart(2, '0')
  const minutes = now.getMinutes().toString().padStart(2, '0')
  currentTime.value = `${hours}:${minutes}`
}

// 更新等待时间
const updateWaitingTime = () => {
  stats.value.avgWaitingTime = Math.floor(Math.random() * 30) + 15
}

// 初始化图表
const initCharts = async () => {
  await nextTick()
  
  waitingChart = echarts.init(document.getElementById('waitingChart'))
  doctorChart = echarts.init(document.getElementById('doctorChart'))
  trendChart = echarts.init(document.getElementById('trendChart'))
  bedChart = echarts.init(document.getElementById('bedChart'))

  // 更新所有图表
  updateWaitingChart()
  updateDoctorChart()
  updateTrendChart()
  updateBedChart()
  updateWaitingTime()
}

// 窗口大小改变时重置图表大小
const handleResize = () => {
  waitingChart?.resize()
  doctorChart?.resize()
  trendChart?.resize()
  bedChart?.resize()
}

onMounted(async () => {
  // 初始化图表
  await initCharts()

  // 开始定时更新
  updateTime()
  timer = window.setInterval(() => {
    updateTime()
    updateWaitingChart()
    updateDoctorChart()
    updateTrendChart()
    updateBedChart()
    updateWaitingTime()
  }, 30000) // 每30秒更新一次

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 清理定时器
  if (timer) {
    clearInterval(timer)
  }

  // 销毁图表实例
  waitingChart?.dispose()
  doctorChart?.dispose()
  trendChart?.dispose()
  bedChart?.dispose()

  // 移除事件监听
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.dashboard {
  min-height: 100vh;
  background: #f0f2f5;
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.back-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin-right: 16px;
}

.back-arrow {
  font-size: 24px;
  color: #333;
}

.header h1 {
  flex: 1;
  margin: 0;
  font-size: 20px;
  color: #333;
}

.time {
  font-size: 16px;
  color: #666;
}

.overview {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 24px;
}

.card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.card-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.card-desc {
  font-size: 12px;
  color: #999;
}

.charts {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.chart-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.chart-header {
  margin-bottom: 16px;
}

.chart-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 4px;
}

.chart-desc {
  font-size: 12px;
  color: #999;
}

.chart-legend {
  display: flex;
  gap: 16px;
  margin-top: 8px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.dot.low { background-color: #52c41a; }
.dot.medium { background-color: #faad14; }
.dot.high { background-color: #ff4d4f; }
.dot.available { background-color: #52c41a; }
.dot.busy { background-color: #faad14; }
.dot.offline { background-color: #ff4d4f; }

.chart {
  height: 300px;
}

@media (max-width: 1200px) {
  .overview {
    grid-template-columns: repeat(2, 1fr);
  }

  .charts {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .dashboard {
    padding: 16px;
  }

  .overview {
    grid-template-columns: 1fr;
  }

  .card-value {
    font-size: 20px;
  }

  .chart {
    height: 250px;
  }
}
</style> 